<template>
  <div
    class="container"
    element-loading-text="正在登录"
    element-loading-background="#000"
    v-loading="!allowedLogin"
  >
    <div class="notlogin-container" v-if="!userInfo">
      <div class="dialog">
        <div class="dialog-title">数字孪生可视化平台</div>
        <div class="dialog-label">用户名</div>
        <el-input
          class="dialog-input"
          v-model="user.userName"
          placeholder="请输入用户名"
        />
        <div class="dialog-label">密码</div>
        <el-input
          class="dialog-input"
          v-model="user.password"
          placeholder="请输入密码"
          show-password
        ></el-input>
        <div
          :class="['dialog-btn', userInputRequired ? 'allowed' : 'not-allowed']"
          @click="login"
        >
          登录
        </div>
      </div>
    </div>
    <div class="login-container" v-else>
      <div class="header">
        <div class="header-top">
          <div class="header-left">数字孪生</div>
          <div>
            <div class="header-right">{{ userInfo.realname }}</div>
            <div class="header-right logout" @click="loginOut">退出登录</div>
          </div>
        </div>
        <div class="header-title">
          <div class="title-CN">数字孪生可视化平台</div>
          <div class="title-EN">Digital Twin Visualization Platform</div>
          <div class="line"></div>
        </div>
      </div>
      <div class="main">
        <div
          class="list"
          v-for="listData in navList"
          :key="listData.id"
          @click="enterScene(listData)"
          @mouseenter="listData.mouseEnter = true"
          @mouseleave="listData.mouseEnter = false"
        >
          <img
            class="list-img"
            :src="listData.imgUrl"
            onerror="this.src = 'images/login/login_base.png'"
          />
          <div class="list-title">{{ listData.name }}</div>
          <div class="list-description" v-show="listData.mouseEnter">
            {{ listData.description }}
          </div>
        </div>
        <div
          class="list"
          v-for="(item, index) in placeholder"
          :key="index"
        ></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, reactive, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  getSenceViewList,
  getUserSence,
  loginRequest,
  loginByRole,
  getUserInfoById,
} from "../api/login";
import { ElMessage } from "element-plus";

const navList = ref([]);
const user = reactive({
  userName: "",
  password: "",
});
const userInfo = ref(null);
const allowedLogin = ref(true);

const userInputRequired = computed(() => user.userName && user.password);
const placeholder = computed(() => new Array(4 - (navList.value.length % 4)));

const route = useRoute();
const router = useRouter();
const routeQuery = route.query;
if (routeQuery.userName && routeQuery.sceneId) {
  window.sessionStorage.setItem("sceneId", routeQuery.sceneId);
  allowedLogin.value = false;
  loginByRole({ userName: routeQuery.userName, senceId: routeQuery.sceneId })
    .then((res) => {
      if (res.state === 1) {
        window.sessionStorage.setItem("userId", res.data.userinfo.id);
        router.push("/");
      } else {
        allowedLogin.value = true;
        ElMessage({
          message: res.msg,
          type: "warning",
        });
        navList.value = [];
      }
    })
    .catch((err) => {
      allowedLogin.value = true;
      console.error(err);
    });
} else {
  let userId = window.sessionStorage.getItem("userId");
  if (userId) {
    getUserInfoById({ id: userId }).then((userData) => {
      userInfo.value = userData;
      getUserScene();
    });
  } else {
    navList.value = [];
  }
}

function login() {
  if (user.userName == "") {
    ElMessage({
      message: "请输入用户名",
      type: "warning",
    });
    return;
  }
  if (user.password == "") {
    ElMessage({
      message: "请输入密码",
      type: "warning",
    });
  }
  allowedLogin.value = false;
  loginRequest(user.userName, user.password)
    .then((userData) => {
      allowedLogin.value = true;
      window.sessionStorage.setItem("userId", userData.id);
      if (userData.isroot === 0) {
        router.push({ path: "/", replace: true });
      } else {
        userInfo.value = userData;
        getUserScene();
      }
    })
    .catch((err) => {
      allowedLogin.value = true;
      ElMessage({
        message: "登录失败",
        type: "warning",
      });
    });
}

function loginOut() {
  userInfo.value = null;
  window.sessionStorage.clear();
  navList.value = [];
}

function getUserScene() {
  const { endtime, id } = userInfo.value;
  let readOnly = false;
  if (endtime && new Date(endtime).getTime() < new Date().getTime()) {
    ElMessage({
      message: "用户使用期限已过期，无法访问场景，请联系管理员",
      type: "warning",
    });
    readOnly = true;
  }
  getUserSence({ userId: id }).then((res) => {
    navList.value = res.mysence.map((item) => {
      return {
        id: item.id,
        imgUrl: item.imgurl || "images/login/login_base.png",
        name: item.name,
        description: item.description,
        readOnly,
        mouseEnter: false,
      };
    });
  });
}

function enterScene(data) {
  if (!data.readOnly)
    window.open(
      `${import.meta.env.VITE_BASE_API}/login?userName=${
        userInfo.value.username
      }&sceneId=${data.id}`,
      "_blank"
    );
}
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
}
.notlogin-container {
  width: 100%;
  height: 100%;
  background-image: url("/images/login/base.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  .dialog {
    position: absolute;
    width: 250px;
    top: 20%;
    right: 10%;
    background-color: rgba(18, 48, 94, 0.8);
    z-index: 10;
    padding: 50px;
    .dialog-title {
      font-size: 24px;
      color: #bed7f6;
      font-weight: bold;
      font-family: Source Han Sans CN-Bold, Source Han Sans CN;
      margin-bottom: 20px;
      letter-spacing: 1px;
    }
    .dialog-label {
      font-size: 14px;
      color: #fff;
      margin: 30px 0 5px 0;
    }

    .dialog-input {
      border-bottom: 1px solid rgba(231, 235, 243, 0.6);
      :deep(.el-input__wrapper) {
        background: transparent;
        box-shadow: none;
        padding: 0;
      }
      :deep(.el-input__inner) {
        background: transparent;
        color: #fff;
        border: none;
        box-shadow: none;
        padding: 0;
      }
      :deep(.is-focus) {
        border: none;
        box-shadow: none;
        padding: 0;
      }
    }
    .dialog-btn {
      width: 100%;
      height: 45px;
      line-height: 45px;
      border-radius: 10px;
      margin-top: 50px;
      color: #fff;
      font-size: 14px;
      text-align: center;
      letter-spacing: 5px;
    }
    .allowed {
      background-color: rgba(35, 93, 164, 1);
      cursor: pointer;
    }
    .not-allowed {
      background-color: rgba(35, 93, 164, 0.5);
      cursor: pointer;
      // cursor: not-allowed;
    }
  }
}
.login-container {
  width: 100%;
  height: 100%;
  overflow: auto;
  .header {
    position: relative;
    width: 100%;
    height: 50vh;
    background-image: url("/images/login/base.png");
    background-size: cover;
    background-repeat: no-repeat;
    .header-top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      height: 50px;
      background-color: #1b2c4d;
      .header-left {
        color: #edf3fa;
        font-size: 20px;
        margin-left: 20px;
      }
      .header-right {
        display: inline-block;
        height: 42px;
        line-height: 42px;
        min-width: 42px;
        border-radius: 21px;
        background-color: #364b74;
        color: #fff;
        font-size: 12px;
        text-align: center;
      }
      .logout {
        width: 80px;
        margin-left: 10px;
        letter-spacing: 1px;
        cursor: pointer;
      }
    }
    .header-title {
      display: flex;
      justify-content: center;
      flex-direction: column;
      position: absolute;
      top: 50px;
      right: 5%;
      width: 280px;
      height: 280px;
      background: rgba(35, 93, 164, 0.8);
      text-align: center;
      .title-CN {
        font-size: 22px;
        color: #edf3fa;
        font-weight: bold;
        letter-spacing: 3px;
        margin-bottom: 5px;
        font-family: Source Han Sans CN-Bold, Source Han Sans CN;
      }
      .title-EN {
        font-size: 14px;
        color: #edf3fa;
        margin-bottom: 5px;
        font-family: Source Han Sans CN-Regular, Source Han Sans CN;
      }
      .line {
        height: 3px;
        background-color: #4b76ae;
        margin: 0 20px;
      }
    }
  }
}
.main {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  padding: 40px;
}
.list {
  position: relative;
  width: 20vw;
  height: 15vw;
  margin: 10px 1vw;
  .list-img {
    width: 100%;
    height: 80%;
    margin: 0;
    padding: 0;
  }
  .list-title {
    display: flex;
    align-items: center;
    justify-content: center;
    color: #235da4;
    font-size: 16px;
    font-weight: 400;
    height: 20%;
  }
  .list-description {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 80%;
    background-color: rgba(0, 0, 0, 0.3);
    color: #fff;
    font-size: 12px;
    padding: 10px;
    box-sizing: border-box;
    cursor: pointer;
  }
}
</style>

<style>
/* 谷歌浏览器记住账号密码后，自动填充输入框，默认输入框样式修改 */
input:-webkit-autofill,
textarea:-webkit-autofill,
select:-webkit-autofill {
  -webkit-text-fill-color: #fff !important;
  -webkit-box-shadow: 0 0 0px 1000px transparent inset !important;
  background-color: transparent;
  background-image: none;
  transition: background-color 50000s ease-in-out 0s;
}
</style>